package controllers

import (
	"MBGAdmin/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

// 基础控制器（所有控制器必须继承此结构体）
type BaseController struct {
	beego.Controller
}

type BaseResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// 响应Json日志
func (c *BaseController) BaseResponse(code int, message string, data ...interface{}) {
	baseResponse := &BaseResponse{
		Code:    code,
		Message: message,
	}
	if len(data) == 0 {
		baseResponse.Data = nil
	} else if len(data) > 1 {
		baseResponse.Data = data
	} else {
		baseResponse.Data = data[0]
	}
	c.Data["json"] = baseResponse
	c.ServeJSON()
}

// 渲染页面
func (c *BaseController) Display(path string) {
	c.TplName = path
	err := c.Render()
	if err != nil {
		beego.Debug("渲染模板失败：", err)
	}
}

// 基础系统初始化
func (c *BaseController) Prepare() {
	o := orm.NewOrm()
	var res []*models.SystemConfigs
	_, _ = o.QueryTable(&models.SystemConfigs{}).Filter("group", "site").All(&res)
	for _, item := range res {
		c.Data[item.Name] = item.Value
	}
	c.Data["now"] = time.Now()
}
